package com.vf.admin.client.service.impl;

import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppUserSettingDao;
import com.vf.admin.client.service.AppUserSettingService;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.utils.BeanUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AppUserSettingServiceImpl implements AppUserSettingService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AppUserSettingDao appUserSettingDao;

    public void saveOrUpdate(AppUserSetting param) {
        if (param.getId() != null && param.getId() > 0) {
            appUserSettingDao.update(param);
        } else {
            appUserSettingDao.add(param);
        }

        String key = String.format(RedisKeys.USER_SETTING, param.getUserId());
        Map<String, Object> objectObjectMap = BeanUtil.objectToMap(param);
        redisUtil.hmset(key, objectObjectMap);
    }

    public Map<String, Object> get(Integer userId) {
        Map<String, Object> stringObjectMap = null;
        String key = String.format(RedisKeys.USER_SETTING, userId);
        Map<Object, Object> hmget = redisUtil.hmget(key);
        if(hmget == null || hmget.size() == 0) {
            AppUserSetting userSetting = appUserSettingDao.getByUserId(userId);

            stringObjectMap = BeanUtil.objectToMap(userSetting);
            redisUtil.hmset(key, stringObjectMap);
        } else {
            stringObjectMap = new HashMap<>();
            for (Map.Entry<Object, Object> entry : hmget.entrySet()) {
                stringObjectMap.put(entry.getKey().toString(), entry.getValue());
            }
        }
        return stringObjectMap;
    }

    @Override
    public List<Map> getUserIdsByHiddenArea() {
        return appUserSettingDao.getUserIdsByHiddenArea();
    }

    @Override
    public List<Map> getUserIdsByHiddenRank() {
        return appUserSettingDao.getUserIdsByHiddenRank();
    }

}
